<template>
  <div class="awards-overview">
    <div class="page-header">
      <h1 class="page-title">奖项总览</h1>
      <p class="page-subtitle">查看所有教职工提交的奖项信息</p>
    </div>

    <el-card>
      <!-- 筛选栏 -->
      <div class="filter-bar">
        <el-select v-model="filterStatus" placeholder="审核状态" style="width: 150px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="待审核" value="PENDING" />
          <el-option label="已通过" value="APPROVED" />
          <el-option label="已驳回" value="REJECTED" />
        </el-select>
        
        <el-select v-model="filterCategory" placeholder="奖项类别" style="width: 150px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="教学成果奖" value="教学成果奖" />
          <el-option label="科技进步奖" value="科技进步奖" />
          <el-option label="社科优秀成果奖" value="社科优秀成果奖" />
          <el-option label="优秀教师" value="优秀教师" />
          <el-option label="先进个人" value="先进个人" />
        </el-select>
        
        <el-select v-model="filterLevel" placeholder="奖项级别" style="width: 150px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="校级" value="校级" />
          <el-option label="省部级" value="省部级" />
          <el-option label="国家级" value="国家级" />
          <el-option label="国际级" value="国际级" />
        </el-select>

        <el-input
          v-model="searchKeyword"
          placeholder="搜索奖项名称或成果名称"
          style="width: 250px;"
          clearable
          @input="handleFilterChange"
        />
      </div>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.total }}</div>
                <div class="stat-label">总奖项数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number pending">{{ stats.pending }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number approved">{{ stats.approved }}</div>
                <div class="stat-label">已通过</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number rejected">{{ stats.rejected }}</div>
                <div class="stat-label">已驳回</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 奖项列表 -->
      <el-table :data="filteredAwards" v-loading="loading" stripe>
        <el-table-column prop="creatorName" label="申请人" width="120" show-overflow-tooltip />
        <el-table-column prop="achievementName" label="成果/项目名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="awardName" label="奖项名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="category" label="奖项类别" width="120" />
        <el-table-column prop="level" label="奖项级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="获奖等级" width="100">
          <template #default="{ row }">
            <el-tag type="success">{{ row.grade || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="awardingDate" label="获奖日期" width="120" />
        <el-table-column prop="awardingOrg" label="颁奖单位" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申报时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              size="small" 
              type="success" 
              v-if="row.status === 'PENDING'"
              @click="handleReview(row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看奖项详情对话框 -->
    <el-dialog v-model="showViewDialog" title="奖项详情" width="800px">
      <div v-if="viewData" class="view-content">
        <el-form label-width="120px" class="view-form">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="申请人">
                <el-input v-model="viewData.creatorName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请部门">
                <el-input v-model="viewData.creatorDepartment" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="奖项名称">
                <el-input v-model="viewData.award.awardName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成果/项目名称">
                <el-input v-model="viewData.award.achievementName" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="奖项类别">
                <el-input v-model="viewData.award.category" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="奖项级别">
                <el-input v-model="viewData.award.level" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="获奖等级">
                <el-input v-model="viewData.award.grade" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="颁奖单位">
                <el-input v-model="viewData.award.awardingOrg" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="获奖日期">
                <el-input v-model="viewData.award.awardingDate" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="证书编号">
                <el-input v-model="viewData.award.certificateNo" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报状态">
                <el-tag :type="getStatusTagType(viewData.award.status)">{{ getStatusText(viewData.award.status) }}</el-tag>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="申报时间">
            <el-input :value="formatDateTime(viewData.award.createdAt)" readonly />
          </el-form-item>

          <el-form-item label="备注" v-if="viewData.award.remarks">
            <el-input v-model="viewData.award.remarks" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 审核信息 -->
          <div v-if="viewData.award.status !== 'PENDING'">
            <el-divider content-position="left">审核信息</el-divider>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="审核人">
                  <el-input v-model="viewData.reviewerName" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核时间">
                  <el-input :value="formatDateTime(viewData.award.reviewTime)" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="审核意见">
              <el-input v-model="viewData.award.reviewOpinion" type="textarea" :rows="3" readonly />
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="showReviewDialog" title="奖项审核" width="600px">
      <el-form ref="reviewFormRef" :model="reviewForm" :rules="reviewRules" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio value="APPROVED">通过</el-radio>
            <el-radio value="REJECTED">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核意见" prop="reviewOpinion">
          <el-input 
            v-model="reviewForm.reviewOpinion" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入审核意见..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showReviewDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="submitting">
            提交审核
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllAwards, reviewAward, getAward } from '@/api/award'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const awards = ref([])
const showViewDialog = ref(false)
const showReviewDialog = ref(false)
const viewData = ref(null)
const currentAward = ref(null)

// 筛选条件
const filterStatus = ref('')
const filterCategory = ref('')
const filterLevel = ref('')
const searchKeyword = ref('')

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 审核表单
const reviewFormRef = ref()
const reviewForm = reactive({
  status: 'APPROVED',
  reviewOpinion: ''
})

// 审核表单验证规则
const reviewRules = {
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  reviewOpinion: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
}

// 统计信息
const stats = computed(() => {
  const total = awards.value.length
  const pending = awards.value.filter(a => a.status === 'PENDING').length
  const approved = awards.value.filter(a => a.status === 'APPROVED').length
  const rejected = awards.value.filter(a => a.status === 'REJECTED').length
  
  return { total, pending, approved, rejected }
})

// 计算属性 - 过滤后的奖项列表
const filteredAwards = computed(() => {
  let filtered = awards.value

  // 状态筛选
  if (filterStatus.value) {
    filtered = filtered.filter(a => a.status === filterStatus.value)
  }
  
  // 类别筛选
  if (filterCategory.value) {
    filtered = filtered.filter(a => a.category === filterCategory.value)
  }
  
  // 级别筛选
  if (filterLevel.value) {
    filtered = filtered.filter(a => a.level === filterLevel.value)
  }

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(a => 
      (a.awardName && a.awardName.toLowerCase().includes(keyword)) ||
      (a.achievementName && a.achievementName.toLowerCase().includes(keyword))
    )
  }

  pagination.total = filtered.length
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  return filtered.slice(start, end)
})

// 获取奖项列表
const fetchAwards = async () => {
  try {
    loading.value = true
    const response = await getAllAwards()
    awards.value = Array.isArray(response) ? response : (response?.data || [])
  } catch (error) {
    console.error('获取奖项列表失败:', error)
    ElMessage.error('获取奖项列表失败')
  } finally {
    loading.value = false
  }
}

// 查看奖项详情
const handleView = async (award) => {
  try {
    // 调用getAward API获取详细信息
    const response = await getAward(award.id)
    if (response && response.award) {
      viewData.value = response
    } else {
      viewData.value = { award: award }
    }
    showViewDialog.value = true
  } catch (error) {
    console.error('获取奖项详情失败:', error)
    ElMessage.error('获取奖项详情失败')
  }
}

// 审核奖项
const handleReview = (award) => {
  currentAward.value = award
  reviewForm.status = 'APPROVED'
  reviewForm.reviewOpinion = ''
  showReviewDialog.value = true
}

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return
  
  try {
    const valid = await reviewFormRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    await reviewAward(currentAward.value.id, {
      status: reviewForm.status,
      reviewOpinion: reviewForm.reviewOpinion
    })
    
    ElMessage.success('审核完成')
    showReviewDialog.value = false
    fetchAwards() // 刷新列表
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  } finally {
    submitting.value = false
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  pagination.page = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
}

const handleCurrentChange = (page) => {
  pagination.page = page
}

// 工具函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  try {
    return new Date(dateTimeStr).toLocaleString('zh-CN')
  } catch {
    return '-'
  }
}

const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已驳回'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  }
  return typeMap[status] || 'info'
}

const getLevelTagType = (level) => {
  const typeMap = {
    '校级': 'info',
    '省部级': 'warning',
    '国家级': 'success',
    '国际级': 'danger'
  }
  return typeMap[level] || 'info'
}

// 挂载时获取数据
onMounted(() => {
  fetchAwards()
})
</script>

<style scoped>
.awards-overview {
  max-width: 1400px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.page-subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.filter-bar {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-number.pending {
  color: #e6a23c;
}

.stat-number.approved {
  color: #67c23a;
}

.stat-number.rejected {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.view-content {
  max-height: 600px;
  overflow-y: auto;
}

.view-form .el-form-item {
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>
